package com.hll.javaweb.servlet.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author hll
 * @create 2022-05-10 13:49
 */
// 以后请求的servlet只要符合这个路径就拦截
@WebFilter("/filter/*")
public class Filter_1 implements Filter {
  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    Filter.super.init(filterConfig);
  }

  @Override
  public void doFilter(
      ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    System.out.println("filter1 in.......");

    servletRequest.setCharacterEncoding("UTF-8");
    servletResponse.setContentType("text/html; charset=UTF-8");
    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    Object user = httpServletRequest.getParameter("user");

    if (user == "hll") {
      httpServletRequest
          .getRequestDispatcher("/pages/hello.html")
          .forward(servletRequest, servletResponse);
    } else {
      // 事实上可以认为以上代码都是前置操作
      filterChain.doFilter(servletRequest, servletResponse); // 放行操作，去执行请求的servlet
      System.out.println("filter1 return..........");
    }

    /* 执行顺序
    filter1 in.......
    filter2 in.......
    这里是servlet........
    filter2 return..........
    filter1 return..........
     */
  }

  @Override
  public void destroy() {
    Filter.super.destroy();
  }
}
